package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/admin/product")
@Slf4j
public class FileUploadController {

    // 配置都放在 nacos 中,所以这里都是从配置中心中读取
    @Value("${minio.endpointUrl}")
    private String endpointUrl;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    // 文件上传
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) {
        String url = null;
        try {
            // 创建 MinIO 客户端对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(this.endpointUrl)
                            .credentials(this.accessKey, this.secretKey)
                            .build();

            // 判断指定的桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.bucketName).build());
            if (!found) {
                // 如果不存在指定的桶则创建
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.bucketName).build());
            } else {
                log.info("当前桶 {} 已存在", this.bucketName);
            }

            // 文件名称
            String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();

            minioClient.putObject(
                    PutObjectArgs.builder().bucket(this.bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            // 拼接上传的文件路径
            url = this.endpointUrl + "/" + this.bucketName + "/" + fileName;
            log.info("图片上传路径: {}", url);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return Result.ok(url);
    }
}
